package com.wzm.moviepic.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


import com.wzm.bean.AdInfo;
import com.wzm.bean.PicInfo;
import com.wzm.db.DBHelper;
import com.wzm.manager.AppConfig;
import com.wzm.manager.AppManager;
import com.wzm.moviepic.AppApplication;
import com.wzm.moviepic.R;
import com.wzm.moviepic.weight.photoview.PhotoView;
import com.wzm.moviepic.weight.photoview.PhotoViewAttacher.OnViewTapListener;
import com.wzm.utils.FileUtils;
import com.wzm.utils.Logger;
import com.wzm.utils.NetworkUtils;
import com.wzm.utils.UtilsTools;

import net.tsz.afinal.FinalBitmap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AdSamplePagerAdapter extends PagerAdapter {

	private Context mContext;
	private ArrayList<PicInfo> pList;	
	private FinalBitmap fb = null;
	private LayoutInflater  mInflater;
	//private String movieid;
	private Map<Integer,Bitmap> bmap = new HashMap<Integer,Bitmap>();
	private AdInfo mAdInfo = null;
	
	
	AdSamplePagerAdapter(Context context,ArrayList<PicInfo> list,AdInfo adinfo)
	{
		mContext = context;
		bmap.clear();
		pList = list;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		fb = AppManager.getInstance(mContext).getFb();
		mAdInfo = adinfo;
		//movieid = mid;
	}
	
	@Override
	public int getCount() {
		return pList.size();
	}

	@Override
	public View instantiateItem(ViewGroup container, int position) {
		
		
		Logger.error("position:"+position);
		if(position==pList.size()-1)
		{//如果到了最后一页（广告）
			View view = mInflater.inflate(R.layout.last_item, container, false); 
			//ArrayList<AdInfo> adbList = AppApplication.getInstance().getAdbList();
			
			final AdInfo adinfo = mAdInfo;
			ImageView ad_icon = (ImageView)view.findViewById(R.id.ad_icon);
			fb.display(ad_icon, adinfo.getIcon());
			TextView tv_name = (TextView)view.findViewById(R.id.ad_name);
			tv_name.setText(adinfo.getName());
			TextView tv_author = (TextView)view.findViewById(R.id.ad_author);
			tv_author.setText(adinfo.getCompany());
			
			TextView tv_intro = (TextView)view.findViewById(R.id.ad_intro);
			tv_intro.setText(adinfo.getIntro());
			
			//删除缓存
			LinearLayout lly_del = (LinearLayout)view.findViewById(R.id.lly_addel);
			
			lly_del.setVisibility(View.GONE);
			lly_del.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//Toast.makeText(mContext, movieid+"删除成功", Toast.LENGTH_SHORT).show();
					
//					if(FileUtils.DeleteMovieDir(movieid))
//					{
//						long rowid = DBHelper.getInstance(mContext).delDownInfo(movieid);
//						if(rowid==1)
//						{			
//							((Activity)mContext).finish();
//							//notifyDataSetChanged(); 
//							Toast.makeText(mContext, "清除成功", Toast.LENGTH_SHORT).show();
//						}
//					}else{
//						Toast.makeText(mContext, "清除成功", Toast.LENGTH_SHORT).show();
//						((Activity)mContext).finish();
//					}				
				}
			});
			
			//离线下载
			
			TextView ad_btn1 = (TextView)view.findViewById(R.id.tv_adbtn1);
			ad_btn1.setText(adinfo.getOpen_url_title());
			LinearLayout lly_addown = (LinearLayout)view.findViewById(R.id.lly_addown);
			
			lly_addown.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Uri uri = Uri.parse(adinfo.getOpen_url());  
					Intent it = new Intent(Intent.ACTION_VIEW, uri);  
					mContext.startActivity(it);
					it = null;
				}
			});
			
			
			LinearLayout lly_adinfo = (LinearLayout)view.findViewById(R.id.lly_adinfo);
			//lly_adinfo.setVisibility(View.GONE);
			lly_adinfo.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent it = new Intent(mContext,AdIntroActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("adinfo", adinfo);
					it.putExtras(bundle);
					mContext.startActivity(it);
					it = null;
					((AdViewPagerActivity)mContext).finish();
				}
			});
			
			LinearLayout lly_backmenu = (LinearLayout)view.findViewById(R.id.lly_backtomenu);
			
			lly_backmenu.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					((AdViewPagerActivity)mContext).finish();
				}
			});
			
			
			
			container.addView(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			return view;
		}
		
		View view = mInflater.inflate(R.layout.movie_item, container, false);   
		

		
		PhotoView movie_img = (PhotoView)view.findViewById(R.id.movie_img);
		
//		if(position!=0)
//		{
//			movie_img.setScaleType(ScaleType.FIT_XY);
//		}
		
		//界面点击事件
		movie_img.setOnViewTapListener(new OnViewTapListener() {
			
			@Override
			public void onViewTap(View view, float x, float y) {
				((AdViewPagerActivity)mContext).touchview();
			}
		});
		
		
		
        final PicInfo pi = pList.get(position);		
        //获取图片链接，判断是否本地有这张图
        //图片文件夹保存的位置
//    	String fileDirPath = Environment.getExternalStorageDirectory().getPath()+AppConfig.MOVIESDIR+movieid+"/";
    	//图片名
//    	String filename =  pi.getImage().substring(pi.getImage().lastIndexOf("/")+1);   	
//    	
//        if(isExists(fileDirPath+filename))
//        {//本地获取
//        	Bitmap bitmap = FileUtils.getLoacalBitmap(fileDirPath+filename);
//        	if(bitmap!=null)
//        	{
//        		movie_img.setImageBitmap(bitmap);
//        		bmap.put(position, bitmap);
//        	}else{
//        		if(NetworkUtils.getNetworkState(mContext)==NetworkUtils.NETWORN_NONE)
//        		{
//        			Toast.makeText(mContext, "Sorry,未检测到网络，请检查",Toast.LENGTH_SHORT).show();
//        		}
//        		fb.display(movie_img,pi.getImage(),movie_img.getWidth(),movie_img.getHeight());
//        	}          	
//        }else{//在线获取
        	if(NetworkUtils.getNetworkState(mContext)==NetworkUtils.NETWORN_NONE)
    		{
    			Toast.makeText(mContext, "Sorry,未检测到网络，请检查",Toast.LENGTH_SHORT).show();
    		}
        	fb.display(movie_img,pi.getImage(),movie_img.getWidth(),movie_img.getHeight());
//        }
        
 
		
        
		
        container.addView(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);  
		return view;
	}
	
	
	


	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {	
		View view = (View) object; 
		container.removeView(view);
		
		Bitmap bitmap = bmap.get(position);
		if(bitmap!=null)
		{
			if(!bitmap.isRecycled())
			{
				//Logger.info("回收"+position);
				bitmap.recycle();
				bitmap = null;
				bmap.remove(position);
			}
		}
		
		view = null;
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}
	
	
	public boolean isExists(String filePath)
	{
		
    	File imgFile = new File(filePath);
		if(imgFile.exists()){
			return true;
		}	
    	return false;
	}
	
}
